package com.example.examapp.controller;

import com.example.examapp.service.impl.WebSocketServer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @version v1.0
 * @package com.example.examapp.controller
 */
@RestController
public class SocketController {


    @Resource
    private WebSocketServer webSocketServer;

    /**
     * @param userName 用户名
     * @param message 消息
     * @throws IOException
     */
    @RequestMapping(value = "/socket", method = RequestMethod.GET)
    public void testSocket1(@RequestParam String userName, @RequestParam String message){
        webSocketServer.sendInfo(userName, message);
    }

    /**
     * @param message 消息
     * @throws IOException
     */
    @RequestMapping(value = "/socket/all", method = RequestMethod.GET)
    public void testSocket2(@RequestParam String message){
        try {
            webSocketServer.onMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/socket/sendAll")
    public void sendAll(@RequestBody Map map) throws IOException {
        System.out.println(map.toString());
        ObjectMapper objectMapper = new ObjectMapper();
        webSocketServer.onMessage(objectMapper.writeValueAsString(map));

    }


}
